<template>
  <div class="fx-tooltip" :class="[position]" :style="tooltipStyle">
    <slot><span style="white-space: pre-line;">{{ titleValue }}</span></slot>
    <div class="fx-tooltip-trip" :style="tripStyle"></div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, ref } from 'vue'
import { PositionPath } from '@/base/types'

export type TooltipPosition = PositionPath

export interface TooltipProps {
  title: string | number;
  position: TooltipPosition;
  width: string | number;
  color: string;
  plain: boolean;
}

export const TooltipPositionArr = ['topLeft', 'top', 'topRight', 'rightTop', 'right', 'rightBottom', 'bottomLeft', 'bottom', 'bottomRight', 'leftTop', 'left', 'leftBottom']

export default defineComponent({
  name: 'fxTooltip',
  props: {
    // 提示文字
    title: {
      type: [String, Number] as PropType<string | number>,
      default: '',
      required: true
    },
    // 提示方向
    position: {
      type: String as PropType<TooltipPosition>,
      default: 'top',
      validator (val: string): boolean {
        return TooltipPositionArr.includes(val)
      }
    },
    width: {
      type: [String, Number] as PropType<string | number>,
      default: 220
    },
    color: {
      type: String as PropType<string>,
      default: null
    },
    plain: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  setup (props: TooltipProps) {
    const titleValue = ref<string | number>(props.title)

    const tooltipStyle = computed(() => {
      return {
        maxWidth: `${props.width}px`,
        backgroundColor: !props.plain ? props.color : '#fff',
        borderColor: props.color,
        color: props.plain ? props.color || '#333' : '#fff'
      }
    })

    const tripStyle = computed(() => {
      return {
        backgroundColor: !props.plain ? props.color : '#fff',
        borderColor: props.color
      }
    })

    const setTitleValue = (val: string | number): void => {
      titleValue.value = val
    }

    return {
      tripStyle,
      titleValue,
      tooltipStyle,
      setTitleValue
    }
  }
})
</script>
